import React, { PureComponent } from "react";

import { PrizeGridWrapper, GridBoxWrapper } from "./style";
import { getDrawPrize_lottery } from "@Services/api";
import { clientType } from "@Utils";
import PrizeResultBox from "../components/PrizeResultBox";
import ContextApp from "@Pages/context";

import { Toast } from "antd-mobile";

class PrizeGrid extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      // 九宫格内容list
      // list: [0, 1, 2, 3, 4, 5, 6, 7],
      // 被选中的格子的ID  // 出发的那个格子
      activedId: "",
      // 中奖ID
      prizeId: null,
      // 获得prizeId之后计算出的动画次数
      times: 0,
      // 当前动画次数
      actTimes: 0,
      // 是否正在抽奖
      isRolling: false,
      isShowResultBox: false,
    };
  }

  freshData() {
    this.context.freshData();
  }

  // 抽奖接口
  async getDrawPrize_lottery() {
    const { activeId, openId, mobile } = this.context;
    let params = {
      id: activeId,
      userKey: openId,
      clientType: clientType(),
      phone: mobile,
    };
    let { code, data = null, msg = "" } = await getDrawPrize_lottery(params);
    if (code === 200) {
      const { prizeDatalist: list } = this.context;
      // 中奖号码
      let i = 0;
      for (i; i < list.length; i++) {
        // debugger
        if (list[i].id == data.id) return { data, i };
      }
    } else {
      // 没中奖
      this.freshData();
      return Toast.show({
        content: msg,
      });
    }
  }

  async handleBegin() {
    // 防止连点
    if (this.state.BeginTimestamp + 2000 > new Date().getTime()) return false;
    this.state.BeginTimestamp = +new Date();

    // 校验登录
    if (!this.context.mobile) return this.context.handleShowLogin(true);

    // 抽奖次数拦截
    if (this.context.surplus == 0) {
      if (this.context.surplusType == 1) {
        return Toast.show({
          content: "今日抽奖次数已用完",
        });
      } else if (this.context.surplusType == 2) {
        // debugger;
        return Toast.show({
          content: "抽奖次数已用完",
        });
      }
    }

    // this.state.isRolling为false的时候才能开始抽，不然会重复抽取，造成无法预知的后果
    if (!this.state.isRolling) {
      // i => 礼品索引
      let { data: prizeData, i: prizeId } = await this.getDrawPrize_lottery();

      if (!prizeData) {
        return;
      }

      // 点击抽奖之后，我个人做法是将于九宫格有关的状态都还原默认
      this.setState(
        {
          activedId: "",
          prizeId,
          times: 0,
          actTimes: 0,
          isRolling: true,
          prizeData,
        },
        () => {
          // 状态还原之后才能开始真正的抽奖
          this.handlePlay();
        }
      );
    }
  }

  handlePlay() {
    // 获得中奖id
    let { prizeId = undefined } = this.state;
    if (prizeId == undefined) return;

    this.setState({
      prizeId,
      activedId: 0,
    });
    // 随机算出一个动画执行的最小次数，这里可以随机变更数值，按自己的需求来
    // let times = this.state.list.length * Math.floor(Math.random() * 5 + 4);
    let times = 38;
    // debugger
    this.setState({
      times,
    });
    // 抽奖正式开始↓↓
    this.begin = setInterval(() => {
      let num;

      if (
        this.state.activedId === this.state.prizeId &&
        this.state.actTimes > this.state.times
      ) {
        // 符合上述所有条件时才是中奖的时候，(两个ID相同)并且(动画执行的次数大于(或等于也行)设定的最小次数)
        clearInterval(this.begin);
        this.setState({
          isRolling: false,
          isShowResultBox: true,
        });
        return;
      }

      // 以下是动画执行时对id的判断
      if (this.state.activedId === "") {
        num = 0;
        this.setState({
          activedId: num,
        });
      } else {
        num = this.state.activedId;
        if (num === 7) {
          // 若是11（最后一格）则下一位为0
          num = 0;
          this.setState({
            activedId: num,
          });
        } else {
          num = num + 1;
          this.setState({
            activedId: num,
          });
        }
      }

      this.setState({
        actTimes: this.state.actTimes + 1,
      });
    }, 60);
  }

  render() {
    const { activedId, prizeData, isShowResultBox, isRolling } = this.state;
    const { surplus, prizeDatalist: list, skins } = this.context;

    return (
      <PrizeGridWrapper skins={skins}>
        <div className="prize">
          <div className="prize__container">
            <div className="container__area">
              <div
                className="begin__btn flexCenter row__item"
                onClick={() => !isRolling && this.handleBegin()}
              >
                <span className="begin_btn_text">抽奖</span>
                {/* -1=无限次 */}
                {surplus >= 0 && (
                  <span className="begin_btn_desc">剩余{surplus}次</span>
                )}
              </div>
              <div className="area__row">
                <RowItem content={list[0]} activedId={activedId} />
                <RowItem content={list[1]} activedId={activedId} />
                <RowItem content={list[2]} activedId={activedId} />
              </div>
              <div className="area__row">
                <RowItem content={list[7]} activedId={activedId} />
                <RowItem content={list[3]} activedId={activedId} />
              </div>
              <div className="area__row">
                <RowItem content={list[6]} activedId={activedId} />
                <RowItem content={list[5]} activedId={activedId} />
                <RowItem content={list[4]} activedId={activedId} />
              </div>
            </div>
          </div>

          {isShowResultBox && (
            <PrizeResultBox
              prizeData={prizeData}
              isShowResultBox={isShowResultBox}
              closeResultBox={(e) => {
                this.setState({ isShowResultBox: false });
                this.freshData();
              }}
            />
          )}
        </div>
      </PrizeGridWrapper>
    );
  }
}

// Item组件--所有格子的操作都可以在此进行，如果这些操作都能与"activedId"关联就更好了
class RowItem extends PureComponent {
  render() {
    const { content, activedId } = this.props;
    return (
      <div
        className={
          activedId === content.index
            ? `row__item row__item__active`
            : `row__item`
        }
        id={`row_item_${content.id}`}
      >
        <div className="prize_single_box">
          {content.imageUrl && <img src={content.imageUrl} fit="contain"></img>}
          <span>{content.name}</span>
        </div>
      </div>
    );
  }
}

// 外部布局
class PrizeGridBox extends PureComponent {
  render() {
    const { skins, handleShowMyPrize, midTitle, mobiNum } = this.context;
    return (
      <GridBoxWrapper skins={skins}>
        <div className="prize_bg">
          {/* 头部小标题 */}
          <div className="mid_title flexCenter noWrap">{midTitle}</div>
          <PrizeGrid />
          <div className="mid_bottom_box flexCenter">
            <div className="mid_bottom_mobi">我的摩币 {mobiNum}</div>
            <div
              className="My_Prize flexCenter"
              onClick={() => handleShowMyPrize(true)}
            >
              我的奖品
            </div>
          </div>
        </div>
      </GridBoxWrapper>
    );
  }
}

PrizeGrid.contextType = ContextApp;
PrizeGridBox.contextType = ContextApp;

export default PrizeGridBox;
